package rov.data;


import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;


public class Controller {
    public static final int OFF = 100;
    public static final int ON = 200;

    private static final int PORT = 32000;

    private ByteBuffer mBuffer;
    private Socket mSock;
    private DataOutputStream mOut;
    private BufferedReader mIn;


    public Controller(String serverName) throws IOException {
        mBuffer = ByteBuffer.allocate(8);

        //try {
            mSock = new Socket(serverName, PORT);
            mOut = new DataOutputStream(mSock.getOutputStream());
            mIn = new BufferedReader(new InputStreamReader(mSock.getInputStream()));
        /*} catch (IOException e) {
            System.err.println("error creating controller");
            e.printStackTrace();
        }*/
    }

    public void close() {
        try {
            mIn.close();
            mOut.close();
        } catch (IOException e) {
            System.err.println("error closing controller I/O streams");
            e.printStackTrace();
        }

        try {
            mSock.close();
        } catch (IOException e) {
            System.err.println("error closing controller socket");
            e.printStackTrace();
        }
    }

    // 0 = full reverse, 100 = off, 200 = full forward
    public void setOutput(int index, int output) {
//System.out.println("transmitting cmd: " + index + ", " + output);

        IntBuffer buf = mBuffer.asIntBuffer();

        buf.put(0, index);
        buf.put(1, output);

        try {
            mOut.write(mBuffer.array());
            mOut.flush();
        } catch (IOException e) {
            System.err.println("error transmitting cmd");
            e.printStackTrace();
        }
    }
}
